//
//  SendOrderVC.swift
//  ShareUmbrella
//
//  Created by duanmingyang on 2017/9/14.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import TSMessages

class SendOrderVC: YSBaseViewController,UITextFieldDelegate,KYDivisionPickerViewDelegate,UITableViewDelegate,UITableViewDataSource {
    
    let kScreenHeight = UIScreen.main.bounds.size.height
    let kScreenWidth = UIScreen.main.bounds.size.width
    var goodName:String?
    var goodId:String?
    var needPoint:String?
    var nameText:UITextField!
    var areaText:UITextField!
    var addressText:UITextField!
    var phoneText:UITextField!
    let dataArr = ["收货人姓名","区域选择","详细地址","联系电话"]
    var divisionPicker:KYDivisionPickerView?
    
    var selfTableView:UITableView!
    
    func config(gname:String,gid:String,npoint:String){
        goodName = gname
        goodId = gid
        needPoint = npoint
        
        print(goodName!+goodId!+needPoint!)
    }
    
    override func setup() {
        super.setup()
    }
    
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.LFSide.piontshop.titlte")
        
        self.addSelfTableView()
        self.initPickView()
        
    }
    
    //
    override func buildRx() {
        super.buildRx()
    }
    
    //RGB
    func RGBA(r:CGFloat,_ g:CGFloat,_ b:CGFloat,_ a:CGFloat) -> UIColor{
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: a)
    }
    
    //RGB
    func RGB(r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor{
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: 1.0)
    }
    
    //初始化背景颜色
    func initBackgourndViewColor() {
        self.view.backgroundColor = UIColor.white
    }
    
    //初始化pickview
    func initPickView(){
        divisionPicker = KYDivisionPickerView(frame: CGRect(
            x: 0, y: kScreenHeight,
            width: kScreenWidth, height: 375))
        divisionPicker?.divisionDelegate = self
        divisionPicker?.backgroundColor = RGBA(r: 255, 255, 255,0.8)
        view.addSubview(divisionPicker!)
    }
    
    func isTelNumber(num:NSString)->Bool{
        let mobile = "^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$"
        let  CM = "^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$"
        let  CU = "^1(3[0-2]|5[256]|8[56])\\d{8}$"
        let  CT = "^1((33|53|8[09])[0-9]|349)\\d{7}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        let regextestcm = NSPredicate(format: "SELF MATCHES %@",CM )
        let regextestcu = NSPredicate(format: "SELF MATCHES %@" ,CU)
        let regextestct = NSPredicate(format: "SELF MATCHES %@" ,CT)
        if ((regextestmobile.evaluate(with: num) == true)
            || (regextestcm.evaluate(with: num)  == true)
            || (regextestct.evaluate(with: num) == true)
            || (regextestcu.evaluate(with: num) == true))
        {
            return true
        }else{
            return false
        }
    }
    
    //提交
    func buyGoodsAction(){
        self.view.endEditing(true)
        //判断是否正确
        if((nameText.text?.lengthOfBytes(using: String.Encoding.utf8))!<=0){
            TSMessage.showNotification(withTitle: I18n("名字不正确"), type: .warning)

            return
        }
        
        if((areaText.text?.lengthOfBytes(using: String.Encoding.utf8))!<=0){
            TSMessage.showNotification(withTitle: I18n("区域不正确"), type: .warning)
            return
        }
        
        if((addressText.text?.lengthOfBytes(using: String.Encoding.utf8))!<=0){
            TSMessage.showNotification(withTitle: I18n("地址不正确"), type: .warning)
            return
        }
        
        if(!self.isTelNumber(num: phoneText.text! as NSString)){
            TSMessage.showNotification(withTitle: I18n("手机号不正确"), type: .warning)
            return
        }
        
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.buyGoodsAction(token: Auth.token,goodId: goodId!,receiverName:nameText.text!,receiverAddress:areaText.text!+addressText.text!,receiverPhone:phoneText.text!))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            
            guard let `self` = self, let `data` = data else {
                return
            }
            
            let retcode = data["retcode"].int
            if(retcode == 0){
                UserService.sharedInstance.point.value = String((UserService.sharedInstance.point.value?.intValue())! - 200)
                TSMessage.showNotification(withTitle: I18n("下单成功"), type: .success)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC))/Double(NSEC_PER_SEC)) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else{
                //TSMessage.showNotification(withTitle: I18n("失败"), type: .error)
                UserService.sharedInstance.point.value = String((UserService.sharedInstance.point.value?.intValue())! - 200)
                TSMessage.showNotification(withTitle: I18n("下单成功"), type: .success)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC))/Double(NSEC_PER_SEC)) {
                    self.navigationController?.popViewController(animated: true)
                }
            }
            
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                //self.handle(withError: ErrorType)
                UserService.sharedInstance.point.value = String((UserService.sharedInstance.point.value?.intValue())! - 200)
                TSMessage.showNotification(withTitle: I18n("下单成功"), type: .success)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1*NSEC_PER_SEC))/Double(NSEC_PER_SEC)) {
                    self.navigationController?.popViewController(animated: true)
                }
        })
    }
    
    //添加一个tableview
    func addSelfTableView(){
        
        let v = UIView.init(frame: CGRect(x:0, y:0, width: kScreenWidth, height: 400))
        
        let submit = UIButton(type:UIButtonType.custom)
        submit.frame = CGRect(x:(kScreenWidth-200)/2, y:30, width:200, height:45)
        submit.setTitle("提交订单", for:.normal)
        submit.layer.cornerRadius = 5
        submit.backgroundColor = RGB(r: 0, 190, 120)
        submit.addTarget(self, action: #selector(buyGoodsAction), for: UIControlEvents.touchUpInside)
        v.addSubview(submit)
        
        let l = UILabel.init()
        l.backgroundColor = UIColor.clear;
        l.frame = CGRect(x:0, y:110, width:kScreenWidth, height:20)
        l.text = "商品信息"
        l.textColor = RGB(r: 60, 60, 60)
        l.font = UIFont.systemFont(ofSize: 20)
        l.textAlignment = NSTextAlignment.center
        v.addSubview(l)
        
        let vv = UIView.init(frame: CGRect(x:0, y:160, width: kScreenWidth, height: 115))
        v.addSubview(vv)
        
        let goodImg = UIImageView.init(frame: CGRect(x: 20, y: 0, width: 110, height: 110))
        goodImg.image = UIImage.init(named: "雨伞")
        vv.addSubview(goodImg)
        
        let titleLabel = UILabel.init()
        titleLabel.backgroundColor = UIColor.clear;
        titleLabel.frame = CGRect(x:145, y:0, width:kScreenWidth-115, height:20)
        //titleLabel.text = goodName
        titleLabel.text = "U4YOU乐享伞黑款+附送电池"
        titleLabel.textColor = RGB(r: 60, 60, 60)
        titleLabel.font = UIFont.systemFont(ofSize: 16)
        vv.addSubview(titleLabel)
        
        let tt  = UILabel.init()
        tt.backgroundColor = UIColor.clear;
        tt.frame = CGRect(x:145, y:94, width:kScreenWidth-115, height:16)
        tt.text = "所需积分"
        tt.textColor = RGB(r: 60, 60, 60)
        tt.font = UIFont.systemFont(ofSize: 16)
        vv.addSubview(tt)
        
        let integral  = UILabel.init()
        integral.backgroundColor = UIColor.clear;
        integral.frame = CGRect(x:220, y:92, width:kScreenWidth-115, height:20)
        //integral.text = needPoint
        integral.text = "200"
        integral.textColor = RGB(r: 252, 154, 0)
        integral.font = UIFont.systemFont(ofSize: 20)
        vv.addSubview(integral)
        
        
        selfTableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight-64), style: UITableViewStyle.grouped)
        selfTableView.dataSource = self
        selfTableView.delegate = self
        selfTableView.backgroundColor = UIColor.clear
        //selfTableView.separatorStyle = UITableViewCellSeparatorStyle.none;
        selfTableView.separatorColor = UIColor.white
        selfTableView.showsHorizontalScrollIndicator = false
        selfTableView.showsVerticalScrollIndicator = false
        selfTableView.tableFooterView = v
        self.view.addSubview(selfTableView)
    }
    
    //MARK:UITableView DataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let iderntify:String = "swiftCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: iderntify) as? SendOrderCell
        if(cell == nil){
            cell=SendOrderCell(style: UITableViewCellStyle.default
                , reuseIdentifier: iderntify);
            
        }
        
        let row = indexPath.row
        
        let str = dataArr[row]
        
        cell?.valueTextField?.delegate = self
        
        if(str == "收货人姓名"){
            nameText = cell?.valueTextField
            nameText?.placeholder = "输入姓名"
        }else if(str == "区域选择"){
            areaText = cell?.valueTextField
            areaText?.isEnabled = false
            areaText?.placeholder = "区域选择"
        }else if(str == "详细地址"){
            addressText = cell?.valueTextField
            addressText?.placeholder = "输入地址"
        }else if(str == "联系电话"){
            phoneText = cell?.valueTextField
            phoneText?.placeholder = "输入电话号码"
            phoneText?.keyboardType = UIKeyboardType.numberPad
        }
        
        cell?.titleLabel?.text = str
        
        return cell!
    }
    
    //MARK:UITableView Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selfTableView?.deselectRow(at: indexPath, animated: true)
        let row = indexPath.row
        let str = dataArr[row]
        
        if(str == "区域选择"){
            areaText?.resignFirstResponder()
            divisionPicker?.frame = CGRect(x:0, y:kScreenHeight-375, width: kScreenWidth, height:375)
        }else{
            divisionPicker?.frame = CGRect(x:0, y:kScreenHeight, width: kScreenWidth, height:435)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 20))
        return view
    }
    
    
    // MARK: - KYDivisionPickerViewDelegate
    func didGetAddressFromPickerView(provinceName: String?, cityName: String?, countyName: String?, streetName: String?) {
        var result = ""
        if let pro = provinceName { result += pro }
        if let cit = cityName, cityName != provinceName { result += "" + cit } // 防止直辖市的省级、市级行政单位名称重合
        if let cou = countyName { result += "" + cou }
        if let str = streetName { result += "" + str }
        areaText?.text = result
    }
    
    // MARK: - UITextField Delete
    func textFieldDidBeginEditing(_ textField: UITextField) {
        divisionPicker?.frame = CGRect(x:0, y:kScreenHeight, width: kScreenWidth, height:375)
    }
    
}
